package com.hxht.cmp.service.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hxht.cmp.common.Constants;
import com.hxht.cmp.entity.Court;
import com.hxht.cmp.service.DeviceService;
import com.hxht.cmp.utils.MD5Utils;
import com.hxht.cmp.utils.http.HttpClientJsonRequest;
import com.hxht.cmp.utils.http.HttpClientResponse;
import com.hxht.cmp.utils.http.HttpClientUtil;
import com.hxht.cmp.utils.http.RequestMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;


@Service
public class DeviceServiceImpl implements DeviceService {
    private final Logger log = LoggerFactory.getLogger(DeviceServiceImpl.class);

    @Override
    public JsonArray getDevStatus(String courtUid) {
        Court court = Constants.COURT_MAP.get(courtUid);
        String url = "http://" + court.getServiceIp() + ":" + Constants.SERVER_PORT + "/getCourtRoomStatus";
        log.info("http协议获取庭审主机信息" + url);
        HttpClientJsonRequest request = new HttpClientJsonRequest(url, RequestMethod.GET);
        Long timestamp = System.currentTimeMillis();
        request.addHeader("Authorization", "basic " + MD5Utils.code(Constants.CLIENT_ID + timestamp + Constants.CLIENT_SCERET));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("appId", Constants.CLIENT_ID);
        jsonObject.addProperty("timestamp", timestamp);
        request.setJsonObject(jsonObject);
        HttpClientResponse response = HttpClientUtil.get(request);
        if (null != response && response.getCode() == 200) {
            String responseText = response.getResponseText();
            if (!StringUtils.isBlank(responseText)) {
                JsonParser jsonParser = new JsonParser();
                JsonElement jsonElement = jsonParser.parse(responseText);
                JsonArray jsonArray = jsonElement.getAsJsonArray();
                return jsonArray;
            } else {
                return null;
            }
        } else {
            log.info("未获取到远程数据");
            return null;
        }
    }
}

